package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Code;
import com.itheima.domain.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController  //等价于@Controller +@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
     /*分页查询*/
    //用restful风格的方式 得改方法上的注解和参数类型上的注解
    @GetMapping("/{currentPage}/{pageSize}")
    public Result pageQuery(@PathVariable Integer currentPage,@PathVariable Integer pageSize){
        PageInfo<User> info = userService.findAll(currentPage, pageSize);

       // return info;
        //修改返回结果
        return info!=null?new Result(Code.QUERY_OK,info):new Result(Code.QUERY_FAIL,"分页查询失败！");
    }

    /*根据id查询*/
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        User user = userService.findById(id);
       // return user ;
        //修改返回结果
        //int a=1/0;
        return user!=null?new Result(Code.QUERY_OK,user):new Result(Code.QUERY_FAIL,"根据id查询失败");
    };

    /*添加用户*/
    @PostMapping
    public Result addUser(User user){
        int count = userService.save(user);
       // return count>0;
        //修改返回结果
        return count>0?new Result(Code.SAVE_OK):new Result(Code.SAVE_FAIL,"添加用户失败");
    };
    /*注意虽然添加和删除的参数是一样的类型 但由于发送请求的方式不同所以不需要在路径前再添加方法名*/

    /*修改用户*/
    @PutMapping
    public Result updateUser(User user){
        int count = userService.update(user);
       // return count>0;
        //修改返回结果
        return count>0?new Result(Code.UPDATE_OK):new Result(Code.UPDATE_FAIL,"修改用户信息失败");
    };

    /*删除用户*/
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id){
        int count = userService.delete(id);
        //return count>0;
        //修改返回结果
        return count>0?new Result(Code.DELETE_OK):new Result(Code.DELETE_FAIL,"删除失败");
    }

    /*用户登录*/  //有点不理解什么时候带方法名
    @GetMapping("/login/{username}/{password}")
    public Result login(@PathVariable String username,@PathVariable String password){
        User loginUser = userService.login(username, password);

        //return loginUser!=null;
        //修改返回结果
        return loginUser!=null?new Result(Code.LOGIN_OK,loginUser):new Result(Code.LOGIN_FAIL,"登录失败");
    }

}
